<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2023/6/2
 * Time: 10:24
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);


namespace App\Common\Business;

use App\Exception\FooException;
use App\Model\UserAddress;
use Hyperf\Di\Annotation\Inject;
use Qbhy\HyperfAuth\AuthManager;

class UserAddressBusiness extends BusBase
{
    protected $obj_model = '';
    /**
     * @var AuthManager
     */
    #[Inject]
    protected $auth;

    public function __construct()
    {
        $this->obj_model = new UserAddress();
    }

    /**
     * @param int $limit
     * @param int $page
     * @return array
     */
    public function getAddressByListInfo(int $limit = 10, int $page = 1): array
    {
        $user_id = $this->auth->guard('jwt')->id();
        if (!$user_id) {
            throw new FooException("请先登录");
        }
        try {
            $result = $this->obj_model
                ->where('user_id', $user_id)
                ->where('user_del', 0)
                ->paginate($limit)->toArray();
        } catch (\Exception $e) {
            throw new FooException("查询失败" . $e->getMessage());
        }
        return $result;
    }

    /**
     * @param array $data
     * @return bool
     */
    public function add(array $data = []): bool
    {
        $user_id = $this->auth->guard('jwt')->id();
        if (!preg_match('/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/', $data['mobile'])) {
            throw new FooException('手机号不正确');
        }
        if ($data['is_default'] == 1) {
            try {
                $this->obj_model->where('user_id', $user_id)
                    ->update(['is_default' => 0]);
            } catch (\Exception $e) {
                throw new FooException("操作失败");
            }
        }
        $insert_data = [
            'name' => $data['name'],
            'addressName' => $data['addressName'],
            'address' => $data['address'],
            'area' => $data['area'],
            'is_default' => $data['is_default'],
            'lat' => $data['lat'],
            'lng' => $data['lng'],
            'user_id' => $user_id,
            'mobile' => $data['mobile']
        ];
        if (!empty($data['id']) && $data['id'] != 0) {
            $insert_data['id'] = intval($data['id']);
        }
        return parent::add($insert_data); // TODO: Change the autogenerated stub
    }

    /**
     * @param int|string $id
     * @return bool
     */
    public function del(int|string $id = 0): bool
    {
        $user_id = $this->auth->guard('jwt')->id();
        try {
            $res = $this->obj_model->where('id', $id)
                ->where('user_id', $user_id)
                ->update([
                    'user_del' => 1
                ]);
        } catch (\Exception $e) {
            throw new FooException("删除失败");
        }
        if (!$res) {
            throw new FooException("删除失败");
        }
        return true;
    }

    /**
     * @param int $user_id
     * @return array
     */
    public function getUserAddressInfo(int $user_id = 0): array
    {
        try {
            $res = $this->obj_model
                ->where('user_id', $user_id)
                ->where('user_del', 0)
                ->orderByDesc('is_default')
                ->orderByDesc('id')
                ->first();
        } catch (\Exception $e) {
            throw new FooException("查询失败");
        }
        if (!$res) {
            return [];
        }
        return $res->toArray();
    }

}